﻿@model GDoc.Web.Models.FilesBrowseModel
@{
    ViewBag.Title = "Browse";
}
@section Head
{
    <link href="@Url.Content("~/Content/jquery.dataTables.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery.dataTables.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.filedrop.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/gdoc.filedrop.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Content/jquery.filedrop.css")" rel="stylesheet" type="text/css" />
    <!--[if lt IE 9]>
        <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script type="text/javascript">
        $(document).ready(function () {
            
            datatable = $("#dataTable").dataTable({
                "bPaginate": false,
                "bLengthChange": false,
                "bFilter": false,
                "bSort": true,
                "bInfo": false,
                "bAutoWidth": false,
                "bProcessing": true,
                "bServerSide": true,
                "sAjaxSource": "@Url.Action("GetFiles", "Files", new { path = Model.Path })",
                "oLanguage": {
                    "sUrl": "@Url.Content("~/Content/dt-lang/datatables.spanish.txt")"
                },
                "fnRowCallback" : function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                    $("td:eq(0)", nRow).html((aData.Name == undefined ? '' : '<div style="max-width:300px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;" title="' + aData.Name + '"><a href="' + aData._Ref + '">' + aData.Name + '</a></div>'));

                    $("td:eq(4)", nRow).html('<div class="tr-actions"><div class="tr-action tr-action-delete" title="Eliminar" onclick="removeFile(this, \'' + aData.FullPath + '\')"></div><tr>');
                },
                "aoColumns": [
                    { "mDataProp": "Name" },
                    { "mDataProp": "Type" },
                    { "mDataProp": "Size" },
                    { "mDataProp": "Modified" },
                    { "mDataProp": null, "bSortable": false }
                ],
                "aaSorting": [[1,'desc']]
            });

            $("#addNewFolder").click(function () {
                $("#dialog:ui-dialog").dialog("destroy");

                $("#add-new-folder-dialog-form").dialog({
                    autoOpen: true,
                    height: 250,
                    width: 500,
                    modal: true,
                    resizable: false,
                    buttons: {
                        "Crear": function () {
                            var bValid = true;

                            bValid = bValid && checkLength($("#name"), "name", 1, 20);

                            bValid = bValid && checkRegexp($("#name"), /^([0-9a-z_-])+$/i, "El nombre de la carpeta sólo puede contener letras, números, guiones y debe comenzar con una letra.");

                            if (bValid) {

                                $.ajax({
                                    url: "@Url.Action("CreateFolder", "Files")",
                                    data: { name : $("#name").val(), path : '@Model.Path'},
                                    type: "POST",
                                    cache: false,
                                    success : function (data) {
                                        datatable.fnDraw();
                                    },
                                    error: function (data) {
                                    }
                                });

                                $(this).dialog("destroy");
                            }
                        },
                        Cancel: function () {
                            $(this).dialog("destroy");
                        }
                    },
                    close: function () {
                        $(this).dialog("destroy");
                    },
                    open: function() { 
                        $(this).parent().find('.ui-dialog-buttonset button:eq(0)').focus();
                    }
                });
            });
        });

        function removeFile(sender, name){
            $(sender).removeClass('tr-action-delete');
            $(sender).addClass('tr-action-loading');
            $.ajax({
                url: "@Url.Action("Remove", "Files")",
                data: { path : name },
                type: "POST",
                cache: false,
                success : function (data) {
                    datatable.fnDraw();
                },
                error: function (data) {
                    datatable.fnDraw();
                }
            });
        }

        $(function () {

            var dropbox = $('#dropbox');
            var message = $('.message', dropbox);
            var uploading = 0;

            dropbox.filedrop({
                // The name of the $_FILES entry:
                paramname: 'pic',

                maxfiles: 10,
                maxfilesize: 2,
                url: '@Url.Action("Upload", "Files", new { path = Model.Path })',

                uploadFinished: function (i, file, response) {
                    uploading--;
                    $.data(file).remove();
                    $("#dataTable").dataTable().fnAddData(response.aaData);
                    if (uploading == 0)
                        showMessage("Arrastre sus archivos aquí.");
                },

                error: function (err, file) {
                    switch (err) {
                        case 'BrowserNotSupported':
                            showMessage('Your browser does not support HTML5 file uploads!');
                            break;
                        case 'TooManyFiles':
                            alert('Too many files! Please select 5 at most! (configurable)');
                            break;
                        case 'FileTooLarge':
                            alert(file.name + ' is too large! Please upload files up to 2mb (configurable).');
                            break;
                        default:
                            break;
                    }
                },

                // Called before each upload is started
                beforeEach: function (file) {
                    uploading++;
                    /*
                    if (!file.type.match(/^image\//)) {
                        alert('Only images are allowed!');

                        // Returning false will cause the
                        // file to be rejected
                        return false;
                    }
                    */
                    return true;
                },

                uploadStarted: function (i, file, len) {
                    createImage(file);
                },

                progressUpdated: function (i, file, progress) {
                    $.data(file).find('.progress').width(progress + '%');
                }

            });

            var template = '<div class="preview">' +
            '<div class="progressHolder">' +
                '<span id="previewFileName"></span>' +
                '<div class="progress">' +
                '</div>' +
            '</div>' +
        '</div>';


            function createImage(file) {

                var preview = $(template);

                var reader = new FileReader();

                reader.onload = function (e) {
                    preview.find("#previewFileName").html(file.name)
                };

                // Reading the file as a DataURL. When finished,
                // this will trigger the onload function above:
                reader.readAsDataURL(file);

                message.hide();
                preview.appendTo(dropbox);

                // Associating a preview container
                // with the file, using jQuery's $.data():

                $.data(file, preview);
            }

            function showMessage(msg) {
                message.html(msg);
                message.show();
            }

        });
    </script>
}
<div class="navigation-panel">
    @Html.ActionLink(Model.Account.Name, "Index", "Account") > <a href="@Url.Action("Browse", "Files", new { path = "" })">
        Archivos</a>
    @{
        string path = String.Empty;
        for (int i = 0; i < Model.DirectoryTree.Length; i++)
        {
            path = GDoc.Domain.Services.FileSystem.Combine(path, Model.DirectoryTree[i]);
            
        @: > <a href="@Url.Action("Browse", "Files", new { path = path })">@Model.DirectoryTree[i]</a>
    }
    }
</div>
<div class="data-panel" style="width: 75%; display: inline-block; float: left;">
    <table cellpadding="0" cellspacing="0" border="0" id="dataTable" width="100%">
        <thead>
            <tr>
                <th>
                    Nombre
                </th>
                <th>
                    Tipo
                </th>
                <th>
                    Tamaño
                </th>
                <th>
                    Modificado
                </th>
                <th>                    
                </th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
<div class="control-panel" style="width: 25%; display: inline-block; float: right;">
    <ul>
        <li><a id="addNewFolder" href="#">Nueva Carpeta</a></li>
    </ul>
    <div id="dropbox">
        <span class="message">Arrastre sus archivos aquí.</span>
    </div>
</div>
<div id="add-new-folder-dialog-form" title="Nueva Carpeta" style="display: none">
    <form>
    <label for="name">
        Nombre</label>
    <input type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" />
    </form>
</div>
